<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 添加角色 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addRoleDialogVisible = true"
            >添加角色</el-button
          >
        </el-col>
      </el-row>
      <!-- 添加角色对话框 -->
      <el-dialog
        title="添加角色"
        :visible.sync="addRoleDialogVisible"
        @close="addRoleDialogClose"
        width="50%"
      >
        <el-form
          ref="addRoleRef"
          :model="addRoleFrom"
          :rules="addRoleFromRules"
        >
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="addRoleFrom.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="addRoleFrom.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addRoleDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addRole">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 角色列表 -->
      <el-table :data="roleslist" border stripe>
        <!-- 展开页 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!-- {{ scope.row }} -->
            <el-row
              class="vcenter"
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
              :class="['bdbottom', i1 === 0 ? 'bdtop' : '']"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row, item1.id)"
                  >{{ item1.authName }}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级与三级权限 -->
              <el-col :span="19">
                <!-- for循环渲染 -->
                <el-row
                  class="vcenter"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                  :class="[i2 === 0 ? '' : 'bdtop']"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightById(scope.row, item2.id)"
                      >{{ item2.authName }}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      closable
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      @close="removeRightById(scope.row, item3.id)"
                      >{{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="min"
              icon="el-icon-edit"
              @click="changeRoleDialog(scope.row)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              size="min"
              icon="el-icon-delete"
              @click="deleteRole(scope.row.id)"
              >删除</el-button
            >
            <el-button
              type="warning"
              size="min"
              icon="el-icon-setting"
              @click="showSetRightDialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 编辑角色弹窗 -->
    <el-dialog
      title="编辑角色"
      :visible.sync="changeRoleDialogVisible"
      @close="changeRoleDialogClose"
      width="50%"
    >
      <el-form
        ref="changeRoleFromRef"
        :model="changeRoleFrom"
        :rules="addRoleFromRules"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="changeRoleFrom.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="changeRoleFrom.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="changeRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="changeRole">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 删除角色使用MessageBox 弹框 -->
    <!-- 分配权限弹窗 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      @close="setRightDialogClosed"
    >
      <!-- 树形控件 -->
      <el-tree
        :data="rightslist"
        :props="treeProps"
        :default-checked-keys="defKeys"
        ref="treeRef"
        show-checkbox
        node-key="id"
        default-expand-all
      >
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定 </el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data () {
    return {
      // 所有角色列表
      roleslist: [],
      // 添加角色对话开关
      addRoleDialogVisible: false,
      // 添加角色对象
      addRoleFrom: {
        roleName: '',
        roleDesc: ''
      },
      // 添加角色表单验证对象
      addRoleFromRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 5, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 5, max: 20, message: '长度在 5 到 20 个字符', trigger: 'blur' }
        ]
      },
      // 编辑角色对话框开关
      changeRoleDialogVisible: false,
      // 编辑角色对象
      changeRoleFrom: {
        roleName: '',
        roleDesc: ''
      },
      // 分配权限对话框开关
      setRightDialogVisible: false,
      // 全部权限列表
      rightslist: [],
      // tree
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      // 当前角色默认选中的节点
      defKeys: [],
      // 当前角色id
      roleId: ''
    }
  },
  created () {
    this.getRoleslist()
  },
  methods: {
    // 确认添加角色
    addRole () {
      this.$refs.addRoleRef.validate(async valid => {
        if (!valid) { return this.$message.error('表单校验未通过') }
        // 表单校验通过发起网络请求
        const { data: res } = await this.$http.post('roles', this.addRoleFrom)
        console.log(res)
        if (res.meta.status !== 201) { return this.$message.error('添加角色失败') }
        // 关闭添加对话框
        this.addRoleDialogVisible = false
        // 刷新页面
        this.getRoleslist()
        this.$message.success('添加角色成功！')
      })
    },
    // 添加角色对话框的回调
    addRoleDialogClose () {
      this.$refs.addRoleRef.resetFields()
    },
    // 打开编辑角色对话框
    changeRoleDialog (obj) {
      this.roleId = obj.id
      this.changeRoleFrom.roleName = obj.roleName
      this.changeRoleFrom.roleDesc = obj.roleDesc
      this.changeRoleDialogVisible = true
    },
    // 确认编辑角色
    async changeRole () {
      const { data: res } = await this.$http.put('roles/' + this.roleId, this.changeRoleFrom)
      console.log(res)
      if (res.meta.status !== 200) { return this.$message.error('修改角色失败') }
      // 关闭对话框
      this.changeRoleDialogVisible = false
      this.changeRoleDialogClose()
      // 刷新列表
      this.getRoleslist()
      this.$message.success('编辑角色成功！')
    },
    // 编辑角色对话框的回调
    changeRoleDialogClose () {
      this.$refs.changeRoleFromRef.resetFields()
    },
    // 删除角色
    async deleteRole (id) {
      // 弹框提示用户
      const confirmResult = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除角色')
      }
      // 发起删除请求
      const { data: res } = await this.$http.delete('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('删除角色失败！')
      }
      // 刷新数据列表
      this.getRoleslist()
      this.$message.success('删除角色成功！')
    },
    // 获取角色列表
    async getRoleslist () {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }
      this.roleslist = res.data
      this.$message.success('获取角色列表成功')
      console.log(res)
    },
    // 根据id删除权限
    async removeRightById (row, rightId) {
      // 弹框提示是否删除
      const confirmResult = await this.$confirm('此操作将删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
      ).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      // 发起删除请求
      const { data: res } = await this.$http.delete('roles/' + row.id + '/rights/' + rightId)
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败')
      }
      row.children = res.data
      this.$message.success('删除成功')
    },
    // 获取全部权限列表
    async showSetRightDialog (role) {
      this.roleId = role.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限列表失败')
      }
      this.rightslist = res.data
      console.log(this.rightslist)
      this.$message.success('获取权限列表成功')
      // 递归获取三级节点
      this.getdefKeys(role, this.defKeys)
      this.setRightDialogVisible = true
    },
    // 通过递归方式获取当前角色三级权限
    getdefKeys (node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => this.getdefKeys(item, arr)
      )
    },
    // 监听分配权限谈弹窗的关闭
    setRightDialogClosed () {
      this.defKeys = []
    },
    // 确认分配权限
    async allotRights () {
      const keys = [...this.$refs.treeRef.getCheckedKeys(), ...this.$refs.treeRef.getHalfCheckedKeys()]
      const idStr = keys.join(',')
      // 确认后发起修改请求
      const { data: res } = await this.$http.post('roles/' + this.roleId + '/rights', { rids: idStr })
      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败')
      }
      this.$message.success('分配权限成功')
      this.getRoleslist()
      this.setRightDialogVisible = false
    }
  }
}
</script>
<style lang="less" scoped>
.el-tag {
  margin: 15px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
